package com.seedog.mq;

import com.seedog.mq.core.MessageQueue;
import com.seedog.mq.core.MessageQueueImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 消息队列工厂类，用于创建消息队列、生产者和消费者实例
 */
public class MessageQueueFactory {
    private static final Logger logger = LoggerFactory.getLogger(MessageQueueFactory.class);
    private static volatile MessageQueueFactory instance;
    private final MessageQueue messageQueue;
    
    // 私有构造函数，实现单例模式
    private MessageQueueFactory() {
        // 创建消息队列实例
        this.messageQueue = new MessageQueueImpl();
        logger.info("MessageQueueFactory initialized");
    }
    
    /**
     * 获取消息队列工厂的单例实例
     * @return 消息队列工厂实例
     */
    public static MessageQueueFactory getInstance() {
        if (instance == null) {
            synchronized (MessageQueueFactory.class) {
                if (instance == null) {
                    instance = new MessageQueueFactory();
                }
            }
        }
        return instance;
    }
    
    /**
     * 获取消息队列实例
     * @return 消息队列实例
     */
    public MessageQueue getMessageQueue() {
        return messageQueue;
    }
    
    /**
     * 创建生产者实例
     * @return 生产者实例
     */
    public Producer createProducer() {
        Producer producer = new ProducerImpl(messageQueue);
        logger.debug("Producer created with ID: {}", producer.getProducerId());
        return producer;
    }
    
    /**
     * 创建指定ID的生产者实例
     * @param producerId 生产者ID
     * @return 生产者实例
     */
    public Producer createProducer(String producerId) {
        Producer producer = new ProducerImpl(messageQueue, producerId);
        logger.debug("Producer created with ID: {}", producer.getProducerId());
        return producer;
    }
    
    /**
     * 创建消费者实例
     * @return 消费者实例
     */
    public Consumer createConsumer() {
        Consumer consumer = new ConsumerImpl(messageQueue);
        logger.debug("Consumer created with ID: {}", consumer.getConsumerId());
        return consumer;
    }
    
    /**
     * 创建指定ID的消费者实例
     * @param consumerId 消费者ID
     * @return 消费者实例
     */
    public Consumer createConsumer(String consumerId) {
        Consumer consumer = new ConsumerImpl(messageQueue, consumerId);
        logger.debug("Consumer created with ID: {}", consumer.getConsumerId());
        return consumer;
    }
    
    /**
     * 关闭消息队列工厂，释放所有资源
     */
    public void shutdown() {
        messageQueue.shutdown();
        logger.info("MessageQueueFactory shutdown");
    }
}